# coding=utf-8
import json
import os
import shutil
import time
from poium.common.logging import logger
import pytest
import click
from conftest import UI_REPORT_DIR, API_REPORT_DIR, APP_REPORT_DIR
from config import RunConfig

'''
说明：
1、用例创建原则，测试文件名必须以“test”开头，测试函数必须以“test”开头，测试类必须以“Test”开头。
2、运行方式：
  > python run_tests.py  (回归模式，生成HTML报告)
  > python run_tests.py -m debug  (调试模式)
'''


def init_env(new_report):
    """
    初始化测试报告目录
    """
    if os.path.exists(new_report):
        shutil.rmtree(new_report)
    os.mkdir(new_report)


@click.command()
@click.option('-m', default=None, help='输入运行模式：run 或 debug.')
@click.option('-rt', default=None, help='输入测试类型：api 或者 ui.')
@click.option('-istest', default=True, help='UI测试中使用环境，默认为测试环境')
def run(m, rt, istest):
    logger.remove()
    RunConfig.RUN = rt
    RunConfig.ISTEST = istest
    now_time = time.strftime("%Y_%m_%d_%H_%M")
    if rt is None or rt.lower() == "ui":
        if m is None or m == "run":
            # **********新建日志************
            RunConfig.NEW_REPORT = os.path.join(UI_REPORT_DIR, now_time)
            case_path = RunConfig.UI_cases_path
            log_file_name = RunConfig.UI_LOG_DIR + f'{RunConfig.NEW_REPORT.split("/")[-1]}.log'
            logger.add(log_file_name)
            logger.info("WEB UI回归模式，开始执行✈✈！")
        elif m == "debug":
            print("debug模式，开始执行！")
            pytest.main(["-v", "-s", '-n=2', RunConfig.UI_cases_path])
            print("运行结束！！")
    elif rt.lower() == 'api':
        if m is None or m == "run":
            # **********新建日志************
            RunConfig.NEW_REPORT = os.path.join(API_REPORT_DIR, now_time)
            log_file_name = RunConfig.API_LOG_DIR + f'{RunConfig.NEW_REPORT.split("/")[-1]}.log'
            logger.add(log_file_name)
            case_path = RunConfig.API_cases_path
            logger.info("API回归模式，开始执行✈✈ ！")
        elif m == "debug":
            print("debug模式，开始执行！")
            pytest.main(["-v", "-s", RunConfig.API_cases_path])
            print("运行结束！！")
    elif rt.lower() == 'app':
        if m is None or m == "run":
            # **********新建日志************
            RunConfig.NEW_REPORT = os.path.join(APP_REPORT_DIR, now_time)
            log_file_name = RunConfig.APP_LOG_DIR + f'{RunConfig.NEW_REPORT.split("/")[-1]}.log'
            logger.add(log_file_name)
            case_path = RunConfig.APP_cases_path
            logger.info("APP回归模式，开始执行✈✈！")
        elif m == "debug":
            print("debug模式，开始执行！")
            pytest.main(["-v", "-s", RunConfig.APP_cases_path])
            print("运行结束！！")
    else:
        raise ValueError('命令行参数错误，无效参数！')
    if m is None or m == "run":
        init_env(RunConfig.NEW_REPORT)
        html_report = os.path.join(RunConfig.NEW_REPORT, 'report.html')
        xml_report = os.path.join(RunConfig.NEW_REPORT, "junit-xml.xml")
        command =["-s", "-v", case_path,
                     "--html=" + html_report,
                     "--junit-xml=" + xml_report,
                     "--self-contained-html",
                     "--maxfail", RunConfig.max_fail,
                     "--reruns", RunConfig.rerun]
        pytest.main(command)
        logger.info("运行结束，生成测试报告♥❤！")
        if 'APP' in case_path:
            ty = 'APP'
        elif 'API' in case_path:
            ty = 'API'
        else:
            ty = 'WEB UI'
        # send_mail(RunConfig.SEND_USER, RunConfig.RECE_USERS, html_report.replace('\\', '/'))
        logger.info(f'发送邮件-{";".join(RunConfig.RECE_USERS)}')
        send_ding(RunConfig.atMobiles, ty)


def send_mail(sender: str, receer: list, filepath: str) -> None:
    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    today = time.strftime('%Y-%m-%d', time.localtime())
    subject = f"{today}的WEB UI测试报告已生成，请查看附件{filepath.split('/')[-1]}"
    if 'API' in filepath:
        subject = f"{today}的API测试报告已生成，请查看附件{filepath.split('/')[-1]}"
    elif 'APP' in filepath:
        if RunConfig.app_name:
            subject = f"{today}的APP-{RunConfig.app_name}测试报告已生成，请查看附件{filepath.split('/')[-1]}"
        else:
            subject = f"{today}的APP测试报告已生成，请查看附件{filepath.split('/')[-1]}"
    with open(filepath, 'rb') as f:
        send_att = f.read()
    att = MIMEText(send_att, 'html', 'utf-8')
    att['Content-Type'] = 'application/octet-stream'
    att['Content-Disposition'] = f'attachment; filename="{filepath.split("""/""")[-1]}"'
    msg = MIMEMultipart()
    msg['subject'] = subject
    msg['from'] = f'{sender.split("::")[1]}'
    msg['to'] = ''.join(receer)
    msg.attach(att)

    smtp = smtplib.SMTP()
    smtp.connect(f'{sender.split("::")[0]}')
    smtp.login(f'{sender.split("::")[1]}', f'{sender.split("::")[2]}')
    smtp.sendmail(f'{sender.split("::")[1]}', ';'.join(receer), msg.as_string())


def send_ding(atmobiles, ty):
    import requests
    headers = {
        'Content-Type': 'application/json',
    }
    params = {
        # 请配置自己组织的access_token
        'access_token': 'e6da488839cb8526f5537da1cd4c8731af66464d903f3712564ee70919339560',
    }
    if atmobiles:
        text = f'{time.strftime("%Y-%m-%d", time.localtime())}的{ty}自动化测试已完成，测试报告请查看您的邮箱。'
    else:
        text = f'{time.strftime("%Y-%m-%d", time.localtime())}的{ty}自动化测试已完成,测试报告已发送到相关人员邮箱，请查收。'
    json_data = {
        'msgtype': 'text',
        'text': {
            'content': text,
        },
        'at': {'atMobiles': atmobiles},
    }
    try:
        response = requests.post('https://oapi.dingtalk.com/robot/send', params=params, headers=headers, json=json_data)
        if response.json()['errcode'] == 0:
            logger.info('钉钉消息发送成功！')
        else:
            logger.error(f'钉钉消息发败，失败原因-{response.json()["errmsg"]}')
    except Exception as e:
        logger.error(f'钉钉消息发送失败！--{e}')


if __name__ == '__main__':
    run()
